from django import forms
from django.contrib.auth.models import User
from face.models import Face 
from bankaccount.models import BankAccount
from character.models import Character
from people.models import People

class SignupForm(forms.Form):
    username = forms.CharField(max_length=30)
    email = forms.EmailField()
    password1 = forms.CharField(max_length=30,widget=forms.PasswordInput(render_value=False))
    password2 = forms.CharField(max_length=30,widget=forms.PasswordInput(render_value=False))
    face = forms.ImageField(required=False)

    def clean_username(self):
        try:
            User.objects.get(username=self.cleaned_data['username'])
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError("This username is already in use. Please choose another.")

    def clean(self):
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError("You must type the same password each time")
        return self.cleaned_data

    def save(self):
		#1. Create new user
        new_user = User.objects.create_user(username=self.cleaned_data['username'],
                                            email=self.cleaned_data['email'],
                                            password=self.cleaned_data['password1'])
        #2. Create bank account
        new_account = BankAccount(fortune=0,owner=new_user)
        new_account.save()
        #3. Create people
        new_people = People(name=self.cleaned_data['username'],controller=new_user)
        new_people.save()
        #4. Create character
        new_character = Character(name=self.cleaned_data['username'],owner=new_people)
        new_character.save()
        #5. Create face
        if 'face' in self.files:
            image = self.files["face"]
            face = Face(owner=new_people,img=image)
            face.save()
        return new_user

class LoginForm(forms.Form):
    username = forms.CharField(max_length=30)
    password = forms.CharField(max_length=30,widget=forms.PasswordInput(render_value=False))
